#include <Document>
#include <Element>
#include <Line>
#include "DocumentProperties.h"

Document::Document(QObject *parent) :
    QObject(parent)
  , m_bModified(false)
  , m_pDocumentProperties(new DocumentProperties)
{
    m_undoStack = new QUndoStack(this);
    restoreDefaultDocumentProperties();
}

const QString &Document::title()
{
    return m_title;
}

void Document::setTitle(const QString &title)
{
    if(m_title == title) return;
    m_title = title;
    emit titleChanged();
}

QPointer<QWidget> Document::ownerView() const
{
    return m_ownerView;
}

void Document::setOwnerView(QPointer<QWidget> ownerView)
{
    m_ownerView = ownerView;
}

bool Document::isModified() const
{
    return m_bModified;
}

const ElementCont &Document::elements() const
{
    return m_elements;
}

void Document::addElement(QPointer<Element> element)
{
    m_elements.append(element);
    connect(element, SIGNAL(elementChanged()), this, SLOT(onElementChanged()));
    emit elementAdded(element);
}

void Document::removeElement(QPointer<Element> element)
{
    m_elements.removeOne(element);
    disconnect(element, SIGNAL(elementChanged()), this, SLOT(onElementChanged()));
    emit elementRemoved(element);
}

QPointer<Line> Document::createLine(const QPointF &start, const QPointF &end)
{
    QPointer<Line> line = new Line(this);
    line->setStart(start);
    line->setEnd(end);

    return line;
}

QPointer<QUndoStack> Document::undoStack() const
{
    return m_undoStack;
}

void Document::restoreDefaultDocumentProperties()
{
    Q_ASSERT(m_pDocumentProperties);
    m_pDocumentProperties->fGridCellSize = 30.0f;
    m_pDocumentProperties->fZoom = 1.0f;
}

float Document::gridCellSize() const
{
    Q_ASSERT(m_pDocumentProperties);
    return m_pDocumentProperties->fGridCellSize;
}

void Document::setCellGridSize(float size)
{
    Q_ASSERT(m_pDocumentProperties);
    m_pDocumentProperties->fGridCellSize = size;
}

float Document::zoom() const
{
    Q_ASSERT(m_pDocumentProperties);
    return m_pDocumentProperties->fZoom;
}

void Document::setZoom(float value)
{
    Q_ASSERT(m_pDocumentProperties);
    m_pDocumentProperties->fZoom = value;

    if(m_pDocumentProperties->fZoom < 0.05f)
    {
        m_pDocumentProperties->fZoom = 0.05f;
    }
}

void Document::setModified(bool bModified)
{
    if(m_bModified == bModified) return;
    m_bModified = bModified;
}

void Document::onElementChanged()
{
    QPointer<Element> element = qobject_cast<Element*>(sender());
    Q_ASSERT(element);
    emit elementChanged(element);
}
